package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：seanyang
 * @date ：Created in 2019/6/7
 * @description ：
 * @version: 1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Reference(interfaceClass = UserService.class)
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password) {
        //log.debug("oms backup,user:{},password:{}",username,password);
        if (userService.login(username, password)) {
            log.debug("login ok!!!");
            return new Result(true, MessageConst.ACTION_SUCCESS);
        } else {
            log.debug("login fail");
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    @RequestMapping("/loginSuccess")
    public Result loginSuccess() {
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    @RequestMapping("/loginFail")
    public Result loginFail() {
        return new Result(false, "登录失败");
    }

    @RequestMapping("/getUsername")
    public Result getUsername() {
        try {
            //从授权框架上下文获取授权对象，再从授权对象获取授权框架用户对象User,最后获取用户名
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = (User) authentication.getPrincipal();
            //log.debug("user:{}",user);
            if (user != null) {
                return new Result(true, MessageConst.ACTION_SUCCESS, user.getUsername());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConst.ACTION_FAIL);
    }

    /**
     * @author ：Miaozb
     * @date ：Update in 2019/7/30
     * 用户界面全部查询和条件查询
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean pageBean) {
        PageResult pageResult = null;
        try {
            pageResult = userService.pageQuery
                    (pageBean.getCurrentPage(), pageBean.getPageSize(), pageBean.getQueryString());
        } catch (Exception e) {
            e.printStackTrace();
            pageResult = new PageResult(0L, new ArrayList());
        }
        return pageResult;
    }

    /**
     * 查询角色列表
     *
     * @return
     */
    @RequestMapping("/findAllRole")
    public Result findAllRole() {
/*
		try{
			List<Role> roles=userService.findAllRole();
			log.debug("@@@roles:{}",roles);
			return new Result(true, MessageConst.ACTION_SUCCESS, roles);
	@RequestMapping("/getUsername")
	public Result getUsername() {
		try{
			//从授权框架上下文获取授权对象，再从授权对象获取授权框架用户对象User,最后获取用户名
			Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
			User user = (User)authentication.getPrincipal();
			//log.debug("user:{}",user);
			if (user != null){
				return new Result(true,MessageConst.ACTION_SUCCESS,user.getUsername());
			}
		}catch(Exception e){
			e.printStackTrace();
			return new Result(false, MessageConst.ACTION_FAIL);
		}
*/

        return userService.findAllRole();
    }

    /**
     * 新增用户
     *
     * @param user    用户信息
     * @param RoleIds 角色id
     * @return
     */
    @RequestMapping("/add")
    @Transactional
    public Result add(@RequestBody com.itheima.health.pojo.User user, Integer[] RoleIds) {
        String password = user.getPassword();
        String encode = passwordEncoder.encode(password);
        user.setPassword(encode);
        log.debug("@@@@@:{}",RoleIds);
        try {
            userService.add(user, RoleIds);

            return new Result(true, MessageConst.ACTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }

    }

    /**
     * 编辑基本信息数据回显
     *
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            com.itheima.health.pojo.User user = userService.findById(id);
            return new Result(true, MessageConst.ACTION_SUCCESS, user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }

    }

    /**
     * 编辑role回显
     *
     * @param id
     * @return
     */
    @RequestMapping("/findRoleIdsByCheckGroupId")
    public Result findRoleIdsByCheckGroupId(Integer id) {

        try {
            List<Integer> roleIds = userService.findRoleIdsByCheckGroupId(id);
            return new Result(true, MessageConst.ACTION_SUCCESS, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }

    }

    /**
     * 修改
     *
     * @param user
     * @param RoleIds
     * @return
     */
    @Transactional
    @RequestMapping("/edit")
    public Result edit(@RequestBody com.itheima.health.pojo.User user, Integer[] RoleIds) {
        String password = user.getPassword();
        String encode = passwordEncoder.encode(password);
        user.setPassword(encode);
        try {
            userService.edit(user, RoleIds);
            return new Result(true, MessageConst.ACTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Transactional
    @RequestMapping("/delById")
    public Result edit(Integer id) {
        try {
            userService.delById(id);
            return new Result(true, MessageConst.ACTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }
    }
}
